package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.*;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")  //等待远程调用
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdService idService;
    @Autowired
    private TimeLineService timeLineService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private VideoApi videoApi;
    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";
    //⽤户是否点赞的前缀
    private static final String COMMENT_USER_LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";
    //⽤户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        //分析: 查询好友的动态,实际上查询时间线表

        //4-- 创建一个分页 装publish 对象
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        // 3-- 分页需要排序  使用pageRequest.of方法
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        //2-创建出查询条件 然后需要分页展示 那么就要创建分页
        Query query = new Query().with(pageable);
        // 1--利用mongodb去查询 符合条件的数据  那么就要创建条件构造器
        List<TimeLine> timeLines = this.mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        //查询到数据 收进行判断 有数据进就装入到publish里面
        if (CollUtil.isEmpty(timeLines)) {
            //没有数据 null  直接返回pageinfo
            return pageInfo;
        }
        //2.3 遍历timelines  获取时间线列表中的发布id的列表
        List<Object> ids = CollUtil.getFieldValues(timeLines, "publishId");

        //2.2 创建查询条件构造器  使用in  降序排列
        Query queryPublish = Query.query(Criteria.where("id").in(ids)).with(Sort.by(Sort.Order.desc("created")));

        //2.1根据查询到的动态id  来查询列表 要创建查询条件构造器
        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }


    /**
     * 发布动态
     *
     * @param publish
     * @return
     */
    @Override
    public String savePublish(Publish publish) {
        if (!ObjectUtil.isAllNotEmpty(publish.getText(), publish.getUserId())) {
            //发布失败
            return null;
        }
        try {
//设置一个主键id
            publish.setId(ObjectId.get());
//设置自增长  mongodb不支持自增长 所以定义一个方法来自增长
            publish.setPid(idService.createId(IdType.PUBLISH));
            publish.setCreated(System.currentTimeMillis());
            //写入到publish表中
            this.mongoTemplate.save(publish);
            //写入相册表
            Album album = new Album();
            album.setId(ObjectId.get());
            album.setCreated(System.currentTimeMillis());
            album.setPublishId(publish.getId());
            //相册表添加到数据库里面
            this.mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());
            //写入到好友的时间线表(异步写入)  调用方法
            this.timeLineService.saveTimeLine(publish.getUserId(), publish.getId());
        } catch (Exception e) {
            log.error("发布动态失败-publish=" + publish, e);
        }
        return publish.getId().toHexString();
    }

    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {

        //创建一个分页 装publish 对象
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
//查询推荐结果数据
        String key = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String data = this.redisTemplate.opsForValue().get(key);
        if (StrUtil.isEmpty(data)) {
            return pageInfo;
        }
        //查询到pid进行分页处理
        List<String> pids = StrUtil.split(data, ',');
        //计算分页
        //[0,10]
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex = startEnd[0];//开始
        int endIndex = Math.min(startEnd[1], pids.size());//结束
        List<Long> pidLongList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidLongList.add(Long.valueOf(pids.get(i)));
        }
        if (CollUtil.isEmpty(pidLongList)) {
            //没有查询到数据
            return pageInfo;
        }
        //根据pid查询publish
        Query query = Query.query(Criteria.where("pid").in(pidLongList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);
        if (CollUtil.isEmpty(pidLongList)) {
            //没哟查询到数据
            return pageInfo;
        }
        pageInfo.setRecords(publishList);

        return pageInfo;
    }

    //====================圈子点赞 评论 喜欢=====================
    @Override
    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //判断该用户是否已经点赞 如果已经点赞就直接返回
        if (this.queryUserIsLike(userId, publishId)) {
            return false;
        }
        //保存comment  评论表的数据    定义一个方法
        boolean result = this.saveComment(userId, publishId, CommentType.Like, null);
        if (!result) {
            //没有保存成功
            return false;
        }
        //需要修改 redis中的点赞数以及是否点赞
        //修改点赞数
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.Like.toString();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
        //用户是否点赞
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, 1);
        return true;
    }

    @Override //取消点赞
    public Boolean disLikeComment(Long userId, String publishId) {
        //先判断用户是否点赞,如果没有返回flase
        if (!this.queryUserIsLike(userId, publishId)) {
            return false;
        }
        //有点赞 就取消点赞和改变点赞数量
        Boolean result = this.removeComment(userId, publishId, CommentType.Like);
        if (!result) {
            //删除不成功 返回flase
            return false;
        }
        //删除成功 就要修改点赞数
        String redisKey = this.getCommentRedisKeyPrefix(publishId); //获取发布人的redisKey
        String hashKey = CommentType.Like.toString(); //获取小key
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);//使得数值减一
        //用户是否点赞
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        this.redisTemplate.opsForHash().delete(redisKey, userHashKey);
        return true;
    }

    @Override //查询数量
    public Long queryLikeCount(String publishId) {
        //从redis中命中查询,如果命中直接返回
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.Like.toString();
        //根据key 取出redis里面的数据
        Object data = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isAllNotEmpty(data)) {
            //数据不为空
            return Convert.toLong(data);
        }
        //redis没有数据 去mongodb查询
        Long count = this.queryCommentCount(publishId, CommentType.Like);
        //把点赞总数 写入redis缓存中 
        this.redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));
        return count;
    }

    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType()));
        return this.mongoTemplate.count(query, CommentType.class);
    }

    @Override //用户是否喜欢
    public Boolean queryUserIsLike(Long userId, String publishId) {
        //从redis 中查询数据
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        Object data = this.redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            //redis 有数据  把里面的数据装换成字符串 和点赞时存的"1"作比较  相等就是点赞 不是相等就不是
            return StrUtil.equals(Convert.toStr(data), "1");
        }
        //在redis没有数据时 去mongodb 去查询
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId).and("commentType").is(CommentType.Like));
        //查询的结果多少条
        long count = this.mongoTemplate.count(query, CommentType.class);
        if (count == 0) {
            //mongodb 也没有数据
            return false;
        }
        //把查询的数据写到redis库中
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");
        return true;
    }

    /**
     * 保存comment数据
     *
     * @return
     */
    private boolean saveComment(Long userId, String publishId, CommentType commentType, String content) {
        try {
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            comment.setUserId(userId);
            comment.setParentId(new ObjectId(publishId));
            //评论类型
            comment.setCommentType(commentType.getType());
            //内容
            comment.setContent(content);
            //时间
            comment.setCreated(System.currentTimeMillis());
            //填充publishUserId
            Publish publish = this.queryPublishById(publishId);
            //todo 其他评论对象,暂时不出来
            if (ObjectUtil.isNotEmpty(publishId)) {
                comment.setPublishUserId(publish.getUserId());
            } else {
                //查询评论
                Comment myComment = this.queryCommentById(publishId);
                //判断是否有评论数
                if (ObjectUtil.isNotEmpty(myComment)) {
                    //有评论时
                    comment.setPublishUserId(myComment.getUserId());
                } else {
                    //查询小视频
                    Video video = this.videoApi.queryVideoById(publishId);
                    if (ObjectUtil.isNotEmpty(video)) {
                        //不为空
                        comment.setPublishUserId(video.getUserId());
                    } else {
                        //其他情况直接返回false
                        return false;
                    }

                }
            }
            //把数据保存在mongodb数据库
            this.mongoTemplate.save(comment);
            return true;
        } catch (Exception e) {
            log.error("保存Comment出错~ userId = " + userId + ", publishId = " +
                    publishId + ", commentType = " + commentType, e);
        }
        return false;
    }

    //查询是否有评论
    private Comment queryCommentById(String publishId) {
        return this.mongoTemplate.findById(new ObjectId(publishId), Comment.class);
    }

    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIKE_REDIS_KEY_PREFIX + userId;
    }


    /**
     * 取消点赞
     *
     * @param userId      用户id
     * @param publishId   发布人id
     * @param commentType 类型   点赞  喜欢 评论
     * @return
     */
    private Boolean removeComment(Long userId, String publishId, CommentType commentType) {
        //删除数据时 需要的条件  对应userId    publishId     commentType
        Query query = Query.query(Criteria.where("userId").is(userId).and("publishId").is(new ObjectId(publishId)).and("commentType").is(commentType));
        //表示操作行数   有删除数据时 getDeletedCount会记录操作数     大于0 表示数据删除成功 点赞取消 反之没有
        return this.mongoTemplate.remove(query, Comment.class).getDeletedCount() > 0;
    }

    //=====================喜欢===========================
    @Override
    public Boolean loveComment(Long userId, String publishId) {
        //查询用户是否已经喜欢
        if (this.queryUserIsLove(userId, publishId)) {
            //已经喜欢 就返回false
            return false;
        }
        //还没点喜欢  保存喜欢数据
        boolean result = this.saveComment(userId, publishId, CommentType.LOVE, null);
        if (!result) {
            //没有保存成功
            return false;
        }
        //喜欢成功后,修改redis中的喜欢数量
        //先把redis的数据取出来 然后加1
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashkey = CommentType.LOVE.toString();
        this.redisTemplate.opsForHash().increment(redisKey, hashkey, 1);
        //标记用户已经喜欢
        hashkey = this.getCommentUserLoveRedisKey(userId);
        this.redisTemplate.opsForHash().put(redisKey, hashkey, "1");
        return result;
    }

    //redis的已经喜欢的key
    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 取消喜欢
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        //先去判断是否喜欢
        if (!this.queryUserIsLove(userId, publishId)) {
            //没有喜欢 就不能取消喜欢
            return false;
        }
        //点了喜欢 删除喜欢
        Boolean result = this.removeComment(userId, publishId, CommentType.LOVE);
        if (!result) {
            //删除失败
            return false;
        }
//删除redis数据库中的记录
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);
        return true;
    }

    /**
     * 查询喜欢数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryLoveCount(String publishId) {
        //先去redis中命中 如果命中的就返回数据 ,没有命中时就mongodb去查询
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hsahKey = CommentType.LOVE.toString();
        Object value = this.redisTemplate.opsForHash().get(redisKey, hsahKey);
        if (ObjectUtil.isNotEmpty(value)) {
            //查询到数据 直接返回
            return Convert.toLong(value);
        }
        //去mongodb里面查询conut总数
        Long count = this.queryCommentCount(publishId, CommentType.LOVE);
        //把总数存入到redis里面
        this.redisTemplate.opsForHash().put(redisKey, hsahKey, String.valueOf(count));
        return count;
    }

    /**
     * 查询用户否喜欢
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        Object value = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            //数据不为空  判断把value转换成字符串和"1"是否相等 相等表示已经喜欢
            return StrUtil.equals(Convert.toStr(value), "1");
        }
        //redis没有查询到数据 查询mongodb
        //设置查询条件
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)).and("userId").is(userId).and("commentType").is(CommentType.LOVE.getType()));
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            //没有数据
            return false;
        }
        //把喜欢数保存到redis数据库里面
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");
        return true;
    }

    //查询评论数 (需要发布时间进行正序排序)
    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType")
                .is(CommentType.COMMENT.getType())).with(pageRequest);
        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);
        PageInfo<Comment> pageInfo = new PageInfo<>();
        //设置一个分页
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        //把数据传递给分页
        pageInfo.setRecords(commentList);
        return pageInfo;
    }


    //发表评论
    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        return this.saveComment(userId, publishId, CommentType.COMMENT, content);
    }

    @Override
    public Long queryCommentCount(String publishId) {
        return this.queryCommentCount(publishId, CommentType.COMMENT);
    }


    /**
     * 查询对我的点赞消息列表
     *
     * @return
     */
    @Override
    public PageInfo<Comment> queryLikeCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId, CommentType.Like, page, pageSize);

    }

    /**
     * 查询对我的喜欢消息列表
     *
     * @return
     */
    @Override
    public PageInfo<Comment> queryLoveCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId, CommentType.LOVE, page, pageSize);
    }

    /**
     * 查询对我的评论消息列表
     *
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId, CommentType.COMMENT, page, pageSize);
    }

    /**
     * 抽取查询列表的公共方法
     *
     * @param userId
     * @param commentType
     * @param page
     * @param pageSize
     * @return
     */
    private PageInfo<Comment> queryCommentListByUser(Long userId, CommentType commentType, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query(Criteria.where("publishUserId").is(userId).and("commentType").is(commentType.getType()));
        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);
        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);
        return pageInfo;
    }

    /**
     * 查询相册表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        //创建分页
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        //查询自己的相册
        List<Album> albumList = this.mongoTemplate.find(query, Album.class, "quanzi_album" + userId);
        if (CollUtil.isEmpty(albumList)) {
            return pageInfo;
        }
        List<Object> publishIdList = CollUtil.getFieldValues(albumList, "publishId");
        //查询条件和降序排序
        Query query1 = Query.query(Criteria.where("id").in(publishIdList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }
}
